package yelmor.comm100.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yelmor.comm100.domain.CoUser;
import yelmor.comm100.domain.CoUserRole;
import yelmor.comm100.repository.CoUserRepository;
import yelmor.comm100.repository.CoUserRoleRepository;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by yel on 4/26/16.
 */
@Service("coUserDetailsService")
public class CoUserDetailsService implements UserDetailsService {

  @Autowired
  private CoUserRepository coUserRepository;

  @Autowired
  private CoUserRoleRepository coUserRoleRepository;

  @Transactional(readOnly = true)
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    CoUser coUser = coUserRepository.findOne(username);
    List<CoUserRole> coUserRoles = coUserRoleRepository.findByUserName(coUser.getUserName());
    Set<GrantedAuthority> grantedAuthoritySet = new HashSet<>();

    for (CoUserRole userRole : coUserRoles) {
      grantedAuthoritySet.add(new SimpleGrantedAuthority(userRole.getRole()));
    }

    List<GrantedAuthority> result = new ArrayList<>(grantedAuthoritySet);
    return new User(coUser.getUserName()
        , coUser.getEnPassword()
        , coUser.getIsEnabled()
        ,true
        ,true
        ,true
        , result);
  }
}
